import subprocess
import psutil

# 定义要设置的内核参数及其值
memory_params = {
    'vm.swappiness': 10,
    'vm.vfs_cache_pressure': 50,
    'vm.overcommit_memory': 1,  # 默认 0 表示 “heuristic” 模式
}

def set_sysctl_param(param, value):
    """设置内核参数并检查结果"""
    try:
        subprocess.run(['sysctl', f'{param}={value}'], check=True, text=True)
        print(f'Successfully set {param} to {value}')
    except subprocess.CalledProcessError as e:
        print(f'Failed to set {param}: {e}')

def update_sysctl_conf(param, value):
    """更新 /etc/sysctl.conf 文件"""
    try:
        with open('/etc/sysctl.conf', 'a') as conf_file:
            conf_file.write(f'{param}={value}\n')
        print(f'Added {param} to /etc/sysctl.conf')
    except IOError as e:
        print(f'Failed to update /etc/sysctl.conf: {e}')

def apply_sysctl_changes():
    """应用所有内核参数更改"""
    for param, value in memory_params.items():
        set_sysctl_param(param, value)
        update_sysctl_conf(param, value)

    # 应用更改
    try:
        subprocess.run(['sysctl', '-p'], check=True, text=True)
        print('Applied changes from /etc/sysctl.conf')
    except subprocess.CalledProcessError as e:
        print(f'Failed to apply changes: {e}')

def check_memory_usage():
    """检查当前内存使用情况"""
    mem = psutil.virtual_memory()
    print(f"Memory Usage: {mem.percent}%")
    print(f"Available Memory: {mem.available / (1024 ** 3):.2f} GB")
    if mem.percent > 80:
        print("Warning: High memory usage!")

if __name__ == '__main__':
    apply_sysctl_changes()
    check_memory_usage()
